package com.steven.sync;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁，：共享锁，排他锁
 *
 * 可同时读，但不可一边读一边写，不可以同时写
 */

public class ReadWriteLock_test {

    static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    //共享锁
    static Lock readLock = readWriteLock.readLock();
    static Lock writeLock = readWriteLock.writeLock();

    public static void  read(Lock lock){
        try {
            lock.lock();
            Thread.sleep(1000);
            System.out.println("read over");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public static void  write(Lock lock,Integer integer){
        try {
            lock.lock();
            Thread.sleep(1000);
            System.out.println("write over");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            new Thread(()->{
                read(readLock);
            }).start();
        }
        for (int i = 0; i < 3; i++) {
            new Thread(()->{
                write(writeLock,22);
            }).start();
        }
    }




}
